/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * Copyright @2008 the original author or authors.
 */
package com.bluestone.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.bluestone.run.ParserManager;

/**
 * A function can accept some parameters and some actions when be refered by other action.
 * @author <a href="mailto:bluesotne.master@gmail.com">daniel.q</a>
 */
public class Function {
	private String name = null;

	private HashMap paras = new HashMap();

	private String script = null;
	
	private Object parent = null;

	/**
	 * Defines the name of the funcion
	 * @return name - String
	 */
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	/**
	 * Defines some parameters of the function
	 * @return paras - HashMap
	 */
	public HashMap getParas() {
		return paras;
	}

	public void setParas(HashMap paras) {
		this.paras = paras;
	}

	/**
	 * Function contents in the format of the XML
	 * @return
	 */
	public String getScript() {
		return script;
	}

	public void setScript(String script) {
		this.script = script;
	}

	public Object getParent() {
		return parent;
	}

	public void setParent(Object parent) {
		this.parent = parent;
	}
	
	/**
	 * The path of the function
	 * @return path - String
	 */
	public String getSearchPath(){
		String path = "";
		if(parent!=null && Library.class.isInstance(parent)){
			path = path + ((Library)parent).getSearchPath();
		}
		path = path+"|"+name;
		
		return path;
	}
	
	/**
	 * Compile the script of the function
	 * @param map HashMap
	 * @return actions - ArrayList
	 */
	public ArrayList compile(HashMap map){
		String temp = script;
		ArrayList actions = new ArrayList();
		Iterator iterator = map.keySet().iterator();
		while(iterator.hasNext()){
			String key = (String)iterator.next();
			String value = (String)map.get(key);
			temp = temp.replaceAll("\\{"+key+"\\}", value);
		}

		temp = "<script>" + temp+"</script>";
		ParserManager parser = new ParserManager();
		actions = parser.parseFunctionScript(temp);
		return actions;
	}

}
